clc;clear;clearvars;
% 随机生成5个数据
num_initial = 5;
num_vari = 5;
% 搜索区间
upper_bound = 5;
lower_bound = -5;
iter = 100;
% 随机生成5个数据,并获得其评估值
sample_x = lhsdesign(num_initial, num_vari).*(upper_bound - lower_bound) + lower_bound.*ones(num_initial, num_vari);
sample_y = f(sample_x);

% 初始化一些参数
pbestx = sample_x;
pbesty = sample_y;
% 当前位置信息presentx
presentx = lhsdesign(num_initial, num_vari).*(upper_bound - lower_bound) + lower_bound.*ones(num_initial, num_vari);
vx = sample_x;
[fmin, gbest] = min(pbesty);

for i = 1 : iter
    r = rand(num_initial, num_vari);
    % pso更新下一步的位置,这里可以设置一下超过搜索范围的就设置为边界
    vx = vx + 2 * r .* (pbestx - presentx) + 2 * r .* (pbestx(gbest, :) - presentx);
    % vx = 2 * r .* (pbestx - presentx) + 2 * r .* (pbestx(gbest, :) - presentx);
    vx(vx > upper_bound) = 5;
    vx(vx < lower_bound) = -5;
    vy = f(vx);
    presentx = vx;
    % 更新每个单独个体最佳位置
    pbestx(vy < pbesty, :) = vx(vy < pbesty, :);
    pbesty = f(pbestx);
    % 更新所有个体最佳位置
    [fmin, gbest] = min(pbesty);
    fprintf("iter %d fmin: %.4f\n", i, fmin);
end